package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.apis.user.IChannelClient;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;

import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.service.WmChannelService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
@Transactional
@Slf4j
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements WmChannelService {
    @Resource
    private WmChannelMapper wmChannelMapper;
    @Resource
    private IChannelClient channelClient;

    /**
     * 查询所有频道
     * @return
     */
    @Override
    public ResponseResult findAll() {

        return ResponseResult.okResult(list());
    }

    /**
     * 保存或更新频道，并同步到用户端
     * @param wmChannel 频道信息
     * @return 保存结果
     */
    @Override
    public boolean saveOrUpdate(WmChannel wmChannel) {
        boolean result = super.saveOrUpdate(wmChannel);

        if (result) {
            try {
                // 同步到用户端
                channelClient.syncChannel(
                        wmChannel.getId(),
                        wmChannel.getName(),
                        wmChannel.getIsDefault(),
                        wmChannel.getStatus()
                );
            } catch (Exception e) {
                log.error("同步频道到用户端失败，频道ID: {}", wmChannel.getId(), e);
            }
        }

        return result;
    }
}